package com.yyw.foodie.Interceptor;

import com.yyw.foodie.constant.BaseConstant;
import com.yyw.foodie.exceptions.NotLoginException;
import com.yyw.foodie.utils.RedisOperator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author 易煜玮
 * @ClassName AuthInterceptor.java
 * @Description 认证拦截器
 * @createTime 2021年06月24日 23:36:00
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisOperator redisOperator;

    /**
     * 请求前拦截用户请求，判断是否登录
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("headerUserToken");
        String userId = request.getHeader("headerUserId");
        log.info("userID: {}, token: {}", userId, token);
        if (StringUtils.isNoneBlank(token, userId)) {
            String redisToken = redisOperator.get(BaseConstant.USER_TOKEN_REDIS_KEY + userId);
            if (StringUtils.isNotBlank(redisToken) && Objects.equals(redisToken, token)) {
                log.info("认证成功");
                return true;
            }
        }
        log.error("认证失败");
        throw new NotLoginException("请登录");
    }
}
